import React, { useState, useEffect } from 'react'
import { PickerView } from "antd-mobile";
import { connect } from "react-redux";
import { List } from "react-virtualized";
import { bindActionCreators } from "redux";
import * as findRoomAction from "../../../store/actions/findRoom";
import axios from "../../../utils/request";
import FindRoomItem from "../../../components/FindRoomItem/index";
// import SearchInp from "../../../components/SearchInp/index";
import styles from "./index.module.scss";
const filterTabs = [
    { id: 1, title: '区域', cols: 3 },
    { id: 2, title: '方式', cols: 1 },
    { id: 3, title: '租金', cols: 1 },
    { id: 4, title: '筛选', cols: 0 },
];

const FindRoom = (props) => {
    const [houseList, setHouseList] = useState([]);//保存房屋总数据的
    const [ind, setInd] = useState(-1);//默认的下标
    const [prckerViewData, setPrckerViewData] = useState([]);
    const [filterData, setFilterData] = useState([[], [], [], []]);//存放筛选出来的数据
    const [searchVal, setSearchVal] = useState("");
    const [datas,setDatas] = useState([]);
    const changeVal = (e) => {
        setSearchVal(e.target.value);
    }
    const searchClick = () => {
        if (searchVal === "") {
            setHouseList(houseList);
        }
        const result = datas.filter(item => item.title.includes(searchVal));
        setHouseList(result);
    }
    useEffect(() => {
        getFindRoomList()
    }, [])
    useEffect(() => {
        getConditionData();
    }, [])
    const getHouseListParams = () => {
        const key = filterData[0][0];
        const value = ['null', undefined].includes(filterData[0][2]) ? filterData[0][1] : filterData[0][2];
        // console.log(key, value);
        let params = { // 请求需要传递的参数
            [key]: value,
            rentType: filterData[1][0],
            price: filterData[2][0],
            more: filterData[3].join(',')
        };
        // console.log('params', params);
        return params;
    };

    const getFindRoomList = () => {//请求房屋总数据
        const params = getHouseListParams();//要传递的参数
        params.cityId = "AREA|88cff55c-aaa4-e2e0";//Id
        axios({ url: "/houses", params: params }).then(result => {
            // console.log(result, "房屋总数据");
            setHouseList(result.list);
            setDatas(result.list);
        })
    }

    const getConditionData = async () => {
        // 房源筛选数据准备
        let prckerViewData = [];
        // 解构出房源筛选数据
        const {
                area,             // 区域
                subway,           // 地铁
                rentType,         // 方式
                price,            // 租金
                roomType,         // 户型
                oriented,         // 朝向
                floor,            // 楼层
                characteristic,   // 房屋亮点
        } = await axios({ url: '/houses/condition', params: { id: 'AREA|88cff55c-aaa4-e2e0' } });
        prckerViewData[0] = [area, subway]//;区域 和 地铁
        prckerViewData[1] = rentType;//租房方式
        prckerViewData[2] = price;// 租金
        prckerViewData[3] = [//更多筛选
            { title: '户型', list: roomType },
            { title: '朝向', list: oriented },
            { title: '楼层', list: floor },
            { title: '房屋亮点', list: characteristic },
        ];
        // 数据处理完成后，更新到状态中
        setPrckerViewData(prckerViewData)

    };
    const virtualList = ({ key, index, style }) => {
        const item = houseList[index];
        return ( // 渲染房屋列表
            <div key={key} style={style}>
                <FindRoomItem {...item}></FindRoomItem>
            </div>
        )
    }
    const onPickerViewChange = (value) => {//下拉改变的事件
        filterData[ind] = value;
        setFilterData(filterData);
    }
    const onMoreFilterClick = (value) => {//更多  筛选
        const index = filterData[3].findIndex(item => item === value);
        if (index === -1) {
            filterData[3].push(value)
        } else {
            filterData[3].splice(index, 1);
        }
        setFilterData(filterData);
    }
    const cancelChoose = () => {// 清除更多筛选条件
        filterData[3] = [];
        setFilterData(filterData);
    }
    const goCityList = ()=>{
        props.history.push("/citylist");
    }
    const goMapFindRoom = ()=>{
        props.history.push("/map")
    }
    const renderFilterContent = () => {
        switch (ind) {
            case 0:
            case 1:
            case 2:
                return <div className={styles.filter_content}>
                    <div className={styles.filter_content_main}>
                        <PickerView
                            data={prckerViewData[ind]}
                            cols={filterTabs[ind].cols}
                            onChange={onPickerViewChange}
                            value={filterData[ind]}
                        ></PickerView>
                    </div>
                    <div className={styles.filter_content_buttons}>
                        <span className={styles.btn_cancel}>取消</span>
                        <span onClick={getFindRoomList} className={styles.btn_confirm}>确定</span>
                    </div>
                </div>;
            case 3:// 更多  筛选
                return <div className={styles.filter_more}>
                    <div className={styles.filter_more_content}>
                        {prckerViewData[3] && prckerViewData[3].map(item =>
                            <div key={item.title}>
                                <h3 className={styles.filter_more_title}>{item.title}</h3>
                                <div className={styles.filter_more_list}>
                                    {item.list.map(item2 =>
                                        <span
                                            key={item2.label}
                                            onClick={() => onMoreFilterClick(item2.value)}
                                            className={filterData[3].includes(item2.value) ? styles.active : ''}
                                        >{item2.label}</span>  ,
                                    )}
                                </div>
                            </div>)}
                    </div>
                    <div className={styles.filter_content_buttons}>
                        <span onClick={cancelChoose} className={styles.btn_cancel}>取消选择</span>
                        <span onClick={getFindRoomList} className={styles.btn_confirm}>确定选中</span>
                    </div>
                </div>;
            default:
                // 返回空标签代表不渲染内容
                return <></>;
        }
    };
    return (
        <div>
            <div className={styles.navbar}>
                <div className={styles.search_inp}>
                    <span onClick={goCityList}>上海 <i className="iconfont icon-xiala"></i></span>
                    <div className={styles.search_con}>
                        <input type="text" placeholder="请在这里搜索区域/商圈" value={searchVal} onChange={changeVal} />
                        <i className="iconfont icon-fangdajing" onClick={searchClick}></i>
                    </div>
                    <p onClick={goMapFindRoom}>地图找房</p>
                </div>
            </div>
            <div className={styles.filter}>
                <div className={styles.filter_tabs}>
                    {filterTabs.map((item, index) =>
                        <span
                            className={[styles.filter_tabs_item, ind === index ? styles.active : ''].join(' ')}
                            key={item.id}
                            onClick={() => { setInd(index) }}>
                            {item.title}
                            <i className="iconfont icon-xiala"></i>
                        </span>
                    )}
                </div>
                {renderFilterContent()}
            </div>
            <div className={styles.houses}>
               {/* 虚拟列表 */} 
                <List
                    width={window.screen.width}
                    height={window.screen.height - 45 - 40 - 50}
                    rowCount={houseList.length}
                    rowHeight={104}
                    rowRenderer={virtualList}
                />
            </div>
            {/* 遮罩层 */}
            <div
                className={[styles.mask_bg, ind !== -1 ? styles.mask_show : ''].join(' ')}
                onClick={() => { setInd(-1) }}
            ></div>
        </div>
    )
}
const mapStateToProps = (state) => {
    return {
        findRoomList: state.findRoom.findRoomList,
        searchRoomList: state.findRoom.searchRoomList
    }
}

const mapDispatchToProps = (dispatch, ownProps) => {
    return bindActionCreators(findRoomAction, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(FindRoom)
